<template>
	<div class="sales-location-management">
		<!-- 面包屑导航 -->
		<el-breadcrumb separator="/">
			<el-breadcrumb-item>首页</el-breadcrumb-item>
			<el-breadcrumb-item>销售地点管理</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 增加 -->
		<div class="add-btn-container">
			<el-button type="primary" icon="el-icon-circle-plus" @click="openAddDialog" size="medium">
				添加销售地点
			</el-button>
		</div>
		<!-- 添加对话框 -->
		<el-dialog title="添加销售地点" :visible.sync="addDialogVisible" width="50%" :before-close="handleAddDialogClose">
			<el-form ref="addFormRef" :model="addForm" :rules="addRules" label-width="100px">
				<!-- 药店名称 -->
				<el-form-item label="药店名称" prop="saleName">
					<el-input v-model="addForm.saleName"></el-input>
				</el-form-item>

				<!-- 联系电话 -->
				<el-form-item label="联系电话" prop="salePhone">
					<el-input v-model="addForm.salePhone"></el-input>
				</el-form-item>
			</el-form>

			<!-- 对话框底部操作按钮 -->
			<div slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleAddSave">保存</el-button>
			</div>
		</el-dialog>
		<!-- 搜索框 -->
		<el-input placeholder="查询（输入要查询的药店名称）" v-model="searchKeyword" class="search-input"
			@input="handleSearch"></el-input>
		<!-- 销售地点列表 -->
		<el-table :data="filteredLocations" stripe style="width: 100%" v-loading="loading">
			<el-table-column prop="saleId" label="药店编号" sortable></el-table-column>
			<el-table-column prop="saleName" label="药店名称"></el-table-column>
			<el-table-column prop="salePhone" label="药店电话"></el-table-column>
			<el-table-column label="注册时间">
				<template slot-scope="scope">
					{{ formatDate(scope.row.createtime) }}
				</template>
			</el-table-column>
			<el-table-column label="更新时间">
				<template slot-scope="scope">
					{{ formatDate(scope.row.updatetime) }}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200">
				<template slot-scope="scope">
					<el-button type="text" icon="el-icon-document" @click="viewDetails(scope.row)">查看</el-button>
					<el-button type="text" icon="el-icon-edit" @click="editLocation(scope.row)">编辑</el-button>
					<el-button type="text" icon="el-icon-delete" @click="delLocation(scope.row.saleId)"
						style="color: #F56C6C;">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 编辑对话框 -->
		<el-dialog title="编辑销售地点" :visible.sync="editDialogVisible" width="50%" :before-close="handleEditDialogClose">
			<el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px">
				<!-- 药店编号（只读） -->
				<el-form-item label="药店编号" prop="saleId">
					<el-input v-model="editForm.saleId" disabled></el-input>
				</el-form-item>

				<!-- 药店名称 -->
				<el-form-item label="药店名称" prop="saleName">
					<el-input v-model="editForm.saleName"></el-input>
				</el-form-item>

				<!-- 联系电话 -->
				<el-form-item label="联系电话" prop="salePhone">
					<el-input v-model="editForm.salePhone"></el-input>
				</el-form-item>
			</el-form>

			<!-- 对话框底部操作按钮 -->
			<div slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleEditSave">保存</el-button>
			</div>
		</el-dialog>
		<!-- 分页 -->
		<div class="pagination">
			<el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange":current-page="currentPage" :page-size="pageSize"
				:total="total" layout="prev, pager, next, jumper" :disabled="loading"></el-pagination>
		</div>
	</div>
</template>

<script>
	import api from '@/api'; // 导入封装的API模块

	export default {
		data() {
			return {
				salesLocations: [], // 原始数据
				filteredLocations: [], // 过滤后的数据（用于展示）
				currentPage: 1,
				pageSize: 10,
				total: 0,
				searchKeyword: '',
				mapVisible: false,
				loading: false,
				searchTimer: null, // 搜索防抖计时器
				editDialogVisible: false, // 编辑对话框显示控制
				editForm: {}, // 编辑表单数据（初始为空对象）
				editRules: { // 表单验证规则
					saleName: [{
						required: true,
						message: '请输入药店名称',
						trigger: 'blur'
					}],
					salePhone: [{
							required: true,
							message: '请输入联系电话',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 15,
							message: '手机号格式不正确',
							trigger: 'blur'
						}
					]
				},
				addDialogVisible: false, // 添加对话框显示控制
				addForm: { // 添加表单数据
					saleName: '',
					salePhone: ''
				},
				addRules: { // 添加表单验证规则
					saleName: [{
						required: true,
						message: '请输入药店名称',
						trigger: 'blur'
					}],
					salePhone: [{
							required: true,
							message: '请输入联系电话',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 15,
							message: '手机号格式不正确（5-15位）',
							trigger: 'blur'
						}
					]
				}
			};
		},

		mounted() {
			this.fetchSalesLocations();
		},

		methods: {
			// 格式化日期
			formatDate(isoString) {
				if (!isoString) return '-';
				try {
					const date = new Date(isoString);
					return date.toLocaleDateString('zh-CN');
				} catch (e) {
					return '-';
				}
			},

			// 搜索处理（带防抖）
			handleSearch() {
				// 清除之前的计时器
				if (this.searchTimer) clearTimeout(this.searchTimer);

				// 设置新的计时器（300ms防抖）
				this.searchTimer = setTimeout(() => {
					if (!this.searchKeyword.trim()) {
						this.filteredLocations = [...this.salesLocations];
						return;
					}

					const keyword = this.searchKeyword.toLowerCase();
					this.filteredLocations = this.salesLocations.filter(item =>
						item.saleName && item.saleName.toLowerCase().includes(keyword)
					);
				}, 300);
			},

			// 获取销售地点数据
			async fetchSalesLocations() {
			  this.loading = true;
			  try {
			    const params = {
			       currentPage: this.currentPage,     // 当前页码
			      pageSize: this.pageSize,       // 每页条数
			      keyword: this.searchKeyword    // 搜索关键词（可选）
			    };
			
			    const response = await api.sale.getSalesLocations(params);
			
			    if (response.code === 0) {
			      this.salesLocations = response.data.list || [];
			      this.filteredLocations = [...this.salesLocations];
			      this.total = response.data.total || 0;  // 从后端获取总记录数
			    } else {
			      this.$message.error(response.message || '获取数据失败');
			    }
			  } catch (error) {
			    console.error('请求出错:', error);
			    this.$message.error('数据加载失败，请稍后重试');
			  } finally {
			    this.loading = false;
			  }
			},


			// 分页变化
			handleCurrentChange(page) {
				this.currentPage = page;
				this.fetchSalesLocations();
			},
			handleSizeChange(size) {
			  this.pageSize = size;
			  this.currentPage = 1;  // 重置为第一页
			  this.fetchSalesLocations();
			},
			// 查看详情
			viewDetails(row) {
				console.log('查看详情:', row);
				// 实际项目中可以跳转到详情页
				// this.$router.push(`/sales-location/detail/${row.saleId}`);
			},

			// 编辑地点
			editLocation(row) {
				console.log('编辑:', row);
				// 实际项目中可以打开编辑对话框
				// this.editForm = {...row};
				// this.editDialogVisible = true;
			},
			// 打开编辑对话框（点击编辑按钮时调用）
			editLocation(row) {
				// 深拷贝当前行数据（避免直接修改原数据）
				this.editForm = JSON.parse(JSON.stringify(row));
				this.editDialogVisible = true;
			},

			// 关闭编辑对话框前重置表单状态
			handleEditDialogClose() {
				this.$refs.editFormRef && this.$refs.editFormRef.resetFields();
				this.editForm = {};
			},

			// 保存编辑内容（调用更新接口）
			async handleEditSave() {
				// 先校验表单
				const isValid = await new Promise(resolve => {
					this.$refs.editFormRef.validate(valid => resolve(valid));
				});
				if (!isValid) return;

				try {
					this.loading = true;
					// 调用更新接口（假设 api.sale.update 对应后端 /sale/update 接口）
					const response = await api.sale.update({
						saleId: this.editForm.saleId, // 必填（主键）
						saleName: this.editForm.saleName, // 可选（新名称）
						salePhone: this.editForm.salePhone // 可选（新电话）
					});

					if (response.code === 0) {
						this.$message.success('修改成功');
						this.editDialogVisible = false; // 关闭对话框
						this.fetchSalesLocations(); // 刷新数据列表
					} else {
						this.$message.error(response.message || '修改失败');
					}
				} catch (error) {
					console.error('修改请求出错:', error);
					this.$message.error('修改失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			},
			// 打开添加对话框
			openAddDialog() {
				this.addDialogVisible = true;
				this.addForm = {
					saleName: '',
					salePhone: ''
				}; // 清空表单
			},
			// 关闭添加对话框前重置表单状态
			handleAddDialogClose() {
				this.$refs.addFormRef && this.$refs.addFormRef.resetFields();
				this.addForm = {
					saleName: '',
					salePhone: ''
				};
			},

			// 保存新增销售地点（调用添加接口）
			async handleAddSave() {
				// 校验表单
				const isValid = await new Promise(resolve => {
					this.$refs.addFormRef.validate(valid => resolve(valid));
				});
				if (!isValid) return;

				try {
					this.loading = true;
					// 调用添加接口（api.sale.add 对应后端 /sale/add）
					const response = await api.sale.add(this.addForm);

					if (response.code === 0) {
						this.$message.success('添加成功');
						this.addDialogVisible = false; // 关闭对话框
						this.fetchSalesLocations(); // 刷新数据列表（新增后自动刷新）
					} else {
						this.$message.error(response.message || '添加失败');
					}
				} catch (error) {
					console.error('添加请求出错:', error);
					this.$message.error('添加失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			},
			// 删除地点（修正后的方法）
			async delLocation(saleId) {
				try {
					// 显示确认对话框
					await this.$confirm('确定要删除这个销售地点吗？', '删除确认', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					});

					this.loading = true;

					// 调用删除API - 使用正确的参数传递方式
					const response = await api.sale.delete({
						saleId
					});

					if (response.code === 0) {
						this.$message.success('删除成功');
						// 重新加载数据（如果当前页只剩一条，返回上一页）
						if (this.salesLocations.length === 1 && this.currentPage > 1) {
							this.currentPage -= 1;
						}
						this.fetchSalesLocations();
					} else {
						this.$message.error(response.message || '删除失败');
					}
				} catch (error) {
					// 用户取消删除时不做处理
					if (error !== 'cancel') {
						console.error('删除失败:', error);
						this.$message.error('删除失败，请稍后重试');
					}
				} finally {
					this.loading = false;
				}
			}
		}
	};
</script>

<style lang="less" scoped>
	.sales-location-management {
		padding: 20px;

		.map-toggle {
			margin-bottom: 15px;
		}

		.search-input {
			margin-bottom: 15px;
		}

		.el-table {
			margin-bottom: 15px;
		}

		.pagination {
			text-align: center;
		}

		// 原样式基础上新增
		.add-btn-container {
			margin: 15px 0;
			display: flex;
			/* 使用 Flex 布局 */
			justify-content: flex-end;
			/* 按钮靠右 */

			.el-button {
				padding: 10px 20px;
				/* 增大内边距 */
				font-size: 14px;
				/* 调整字体大小 */
			}
		}
	}
</style>